package edu.mju.vod.service.impl;

import com.aliyun.vod.upload.impl.UploadVideoImpl;
import com.aliyun.vod.upload.req.UploadStreamRequest;
import com.aliyun.vod.upload.resp.UploadStreamResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.vod.model.v20170321.DeleteVideoRequest;
import edu.mju.commonutils.ReturnCode;
import edu.mju.servicebase.exception.StuException;
import edu.mju.vod.service.VodService;
import edu.mju.vod.utils.ConstVodUtils;
import edu.mju.vod.utils.InitVodClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.List;

/**
 * @Author:wyp
 * @Date:2020/9/13 17:46
 */
@Service
public class VodServiceImpl implements VodService {
    @Override
    public String uploadVideo(MultipartFile multipartFile) {
        try{
            String fileName = multipartFile.getOriginalFilename() ;
            String title = fileName.substring(0,fileName.lastIndexOf(".")) ;
            InputStream inputStream = multipartFile.getInputStream();
            //UploadStreamRequest(id,密钥,文件名,原始文件名称,文件输入流)
            UploadStreamRequest request = new UploadStreamRequest(ConstVodUtils.KEY_ID, ConstVodUtils.KEY_SECRET, title, fileName, inputStream);

            UploadVideoImpl uploader = new UploadVideoImpl();
            UploadStreamResponse response = uploader.uploadStream(request);

            String videoId = null ;
            if (response.isSuccess()) {
                videoId = response.getVideoId() ;
            } else {
                videoId = response.getVideoId() ;
            }
            return videoId;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 删除多个视频
     * @param videoIdList 视频id列表
     */
    @Override
    public void removeAllVideo(List videoIdList) {
        try {
            //初始化对象
            DefaultAcsClient defaultAcsClient = InitVodClient.initVodClient(ConstVodUtils.KEY_ID, ConstVodUtils.KEY_SECRET);
            //创建删除视频request对象
            DeleteVideoRequest request = new DeleteVideoRequest();
            //向request设置视频id
            request.setVideoIds(StringUtils.join(videoIdList,","));
            //使用初始化对象的方法实现删除
            defaultAcsClient.getAcsResponse(request);
        }catch (Exception e){
            e.printStackTrace();
            throw new StuException(20001,"删除视频失败");
        }
    }
}
